package com.itboye.jinpuyiyuan.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.MainThread;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.itboye.jinpuyiyuan.MainActivity;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.activity.login.LoginOrRegisterActivity;
import com.itboye.jinpuyiyuan.activity.me.FeedBackActivity;
import com.itboye.jinpuyiyuan.activity.me.HospitalActivity;
import com.itboye.jinpuyiyuan.activity.me.IllRecordActivity;
import com.itboye.jinpuyiyuan.activity.me.MedicaRecordsActivity;
import com.itboye.jinpuyiyuan.activity.me.PaymentRecordActivity;
import com.itboye.jinpuyiyuan.activity.me.PersonInfoActivity;
import com.itboye.jinpuyiyuan.activity.me.PrescriptionRecordActivity;
import com.itboye.jinpuyiyuan.activity.me.RealNameActivity;
import com.itboye.jinpuyiyuan.activity.me.SetUpActivity;
import com.itboye.jinpuyiyuan.activity.me.TestRecordActivity;
import com.itboye.jinpuyiyuan.app.MyApplication;
import com.itboye.jinpuyiyuan.base.BaseFragment;
import com.itboye.jinpuyiyuan.utils.logincontroller.LoginController;
import com.itboye.jinpuyiyuan.utils.logincontroller.LoginedState;
import com.itboye.jinpuyiyuan.utils.logincontroller.UnLoginState;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.widget.CircleImageView;
import com.itboye.jinpuyiyuan.widget.FilterUtil;
import com.itboye.jinpuyiyuan.widget.IsStringSPUtils;
import com.itboye.jinpuyiyuan.widget.LoweLinearLayout;
import com.itboye.jinpuyiyuan.widget.TranslucentScrollView;
import com.itboye.jinpuyiyuan.widget.XImageLoader;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.RunnableFuture;


/**
 * 我的
 */
public class MeFragment extends BaseFragment {
    private CircleImageView logoImg;
    private TextView tvNikeNmae;
    private TranslucentScrollView meSV;
    private LinearLayout doctorSort;
    private ImageView doctorRecord, medicalHistoryRecord, payRecord;
    private ImageView doctorRegisterImg, drugImg, testImg, hospitalImg, opinionImg, contactImg;
//    LinearLayout me_medica_records,me_payment_records,me_ill_records;//就诊记录，缴费记录，病史记录
//    RelativeLayout me_real_name,me_feed_back,testRecordRl,prescriptionRl,hospitalRl;//实名认证,意见反馈,化验记录
    LoweLinearLayout me_medica_records,me_payment_records,me_ill_records,me_real_name,me_feed_back,testRecordRl,prescriptionRl,hospitalRl,contactUsRL;
    private RelativeLayout  topBar;

    private ImageView leftImg, leftImg1, rightImg1, rightImg;
    private TextView leftTv1, leftTv, tvTitle1, tvTitle,doctorVertifyTv;
    private boolean isMeasured = false;
    private float distance;
    private  BroadcastReceiver receiver,headReceiver;
    private boolean isDownload=false;
    private String uid,nick;
    private Bitmap logoBit;//个人信息图片的bit
    private PopupWindow callPop;
    private String logoUrl;
    @Override
    public int initView() {
        //判断加载医生端还是病人端

        return R.layout.fragment_me;

    }

    @Override
    public void onMyActivityCreated() {

//        leftImg.setVisibility(View.GONE);
        leftImg1.setVisibility(View.GONE);
//        leftTv.setVisibility(View.GONE);
        leftTv1.setVisibility(View.GONE);
//        tvTitle.setVisibility(View.GONE);
        tvTitle1.setVisibility(View.GONE);
//        tvTitle.setText("我的");
//        tvTitle1.setText("我的");

        init();
        initBroadcast();


//        ViewTreeObserver observer = doctorSort.getViewTreeObserver();
//        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
//            public boolean onPreDraw() {
//                if (!isMeasured) {
//                    distance = doctorSort.getTop();
//                    meSV.setTransView(toobar, getActivity().getResources().getColor(R.color.black), 0, (int) distance);
//                    meSV.hindView(topBar);
//                    isMeasured = true;
//                }
//                return true;
//            }
//        });

//        Log.d("=========",distance+"");
//

    }

//    private void initViewData() {
//        logoUrl= (String) SPUtils.get(getActivity().getApplication(),null,"personLogo","");
//        uid= (String) SPUtils.get(getActivity().getApplication(),null,Const.UID,"");
//        nick= (String) SPUtils.get(getActivity().getApplication(),null,Const.NICK,"");
//
//        //已登录
////            logoImg.setImageBitmap(XImageLoader.loadBitmap(Const.DoctorImg+uid));
//        if (logoUrl==null||logoUrl.equals("")){
//            Thread thread= new Thread() {
//                @Override
//                public void run() {
//                    logoBit=returnBitmap(Const.DoctorImg+uid);
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            logoImg.setImageBitmap(logoBit);
//                        }
//                    });
//                }
//            };
//            thread.start();
//            return;
//        }else {
//            Log.d("===xiugai==","hahahaha");
//            Bitmap bm = BitmapFactory.decodeFile(logoUrl);
//            logoImg.setImageBitmap(bm);
//        }
//        Log.d("nick==",nick);
//        tvNikeNmae.setText(nick);
//
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//      getActivity().unregisterReceiver(receiver);

    }

    //设置头像
    public void init(){
        logoUrl= (String) SPUtils.get(getActivity().getApplication(),null,"personLogo","");

        uid= (String) SPUtils.get(getActivity().getApplication(),null,Const.UID,"");
        nick= (String) SPUtils.get(getActivity().getApplication(),null,Const.NICK,"");
        if ((boolean)SPUtils.get(getActivity().getApplication(),uid,"isVerify",false)){
            doctorVertifyTv.setText("已认证");
            doctorVertifyTv.setTextColor(getActivity().getResources().getColor(R.color.title_blue));
        }else {
            doctorVertifyTv.setText("实名制认证");
            doctorVertifyTv.setTextColor(getActivity().getResources().getColor(R.color.main_orange));
        }


        Log.d("uid======gai",uid);
        Log.d("uid======gai",nick);
        if (uid==null||uid.equals("")){//未登录或已退出登录
            Log.d("==login in=","false"+"");
            logoImg.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.login_logo));
//                Glide.with(getActivity()).load(Const.DoctorImg+SPUtils.get(getActivity().getApplication(),null,Const.ID,1001)).into(logoImg);
            tvNikeNmae.setText("请先登录");
        }else { //已登录
//            logoImg.setImageBitmap(XImageLoader.loadBitmap(Const.DoctorImg+uid));
            if (logoUrl==null||logoUrl.equals("")){
                Thread thread= new Thread() {
                    @Override
                    public void run() {
                        logoBit=returnBitmap(Const.DoctorImg+uid);
                        if (logoBit==null){
                            getActivity().runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                logoImg.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.login_logo));
                                                            }
                                                        });

                        }else {
                            Log.d("===logoUrl==",Const.DoctorImg+uid);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    logoImg.setImageBitmap(logoBit);
                                }
                            });
                        }

                    }
                };
                thread.start();
            }else {
                Bitmap bm = BitmapFactory.decodeFile(logoUrl);
                Log.d("===logoUrl==",logoUrl);
                logoImg.setImageBitmap(bm);
            }
            tvNikeNmae.setText(nick);
        }

    }

    //初始化广播
    public void initBroadcast(){
       //登录登出的广播
        receiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("=======",nick);
                init();
//                if (intent.getAction()==FilterUtil.EXITLOGIN){
//                    logoImg.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.login_logo));
////                Glide.with(getActivity()).load(Const.DoctorImg+SPUtils.get(getActivity().getApplication(),null,Const.ID,1001)).into(logoImg);
//                    tvNikeNmae.setText("请登录");
//                }else if (intent.getAction() ==FilterUtil.LOGIN){
//                    logoImg.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.login_logo));
////                Glide.with(getActivity()).load(Const.DoctorImg+SPUtils.get(getActivity().getApplication(),null,Const.ID,1001)).into(logoImg);
//                    tvNikeNmae.setText("请登录");
//                }

            }
        };
        //修改头像的广播
        headReceiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("===xiugai==","laile");
               init();
                Glide.with(getActivity()).load(Const.DoctorImg+uid).into(logoImg);

            }
        };
        getActivity().registerReceiver(headReceiver,new IntentFilter(FilterUtil.HEAD));
        getActivity().registerReceiver(receiver,new IntentFilter(FilterUtil.EXITLOGIN));
        getActivity().registerReceiver(receiver,new IntentFilter(FilterUtil.LOGIN));

    }
    @Override
    public void onClick(View v) {
        Intent intent=null;
        switch (v.getId()) {
            case R.id.rightImg:
            case R.id.rightImg1://设置

                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                    intent = new Intent(getActivity(), SetUpActivity.class);
                    startActivity(intent);
                }
                break;
           // case R.id.doctorRecord:
            case R.id.me_medica_records://就诊记录
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                    intent = new Intent(getActivity(), MedicaRecordsActivity.class);
                    startActivity(intent);
                }
                break;
           // case R.id.payRecord:
            case R.id.me_payment_records://缴费记录
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                    intent = new Intent(getActivity(), PaymentRecordActivity.class);
                    startActivity(intent);
                }
                break;
           // case R.id.medicalHistoryRecord:
            case R.id.me_ill_records://病史记录

                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                    intent = new Intent(getActivity(), IllRecordActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.me_real_name://实名认证
            case R.id.doctorVertifyTv:
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                    intent=new Intent(getActivity(),RealNameActivity.class);
                    startActivityForResult(intent,100);
                }

                break;
            case R.id.prescriptionRl://处方记录
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                    intent = new Intent(getActivity(), PrescriptionRecordActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.testRecordRl://化验记录
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                    intent = new Intent(getActivity(), TestRecordActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.hospitalRl://住院记录
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                intent=new Intent(getActivity(),HospitalActivity.class);
                startActivity(intent);}
                break;
            case R.id.me_feed_back://意见反馈
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                    intent = new Intent(getActivity(), FeedBackActivity.class);
                    startActivity(intent);
                }
                break;

           //个人资料
            case R.id.logoImg:
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                }else {
                    LoginController.setLoginState(new LoginedState());
                }
                LoginController.PersonnalInfomaton(getActivity(),null);
                break;
            //联系我们
            case R.id.contactUsRL:
           // case R.id.contactUsTv:
            case R.id.contactImg:
                showCallPhonePop();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==100&&resultCode==200){
            if (data.getBooleanExtra("isSuccess",false)){
                doctorVertifyTv.setText("已认证");
                doctorVertifyTv.setTextColor(getActivity().getResources().getColor(R.color.title_blue));
            }else {
                doctorVertifyTv.setText("实名制认证");
                doctorVertifyTv.setTextColor(getActivity().getResources().getColor(R.color.main_orange));
            }
        }
    }

    public void showCallPhonePop(){
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_callphone, null);
        callPop=new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);

        callPop.setAnimationStyle(R.style.popupwindow_anim_style);
        callPop.setFocusable(true);
        TextView cancelTv=inflate.findViewById(R.id.cancelTv);
        TextView callTv= inflate.findViewById(R.id.callTv);
        final TextView callNumberTv=inflate.findViewById(R.id.callNumberTv);
        inflate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callPop.dismiss();
            }
        });
        //取消
        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               callPop.dismiss();
            }
        });
        //呼叫
        callTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+"1008611"));
                startActivity(intent);
                callPop.dismiss();
            }
        });
        inflate.setFocusable(true);//comment by danielinbiti,设置view能够接听事件，标注1
        inflate.setFocusableInTouchMode(true); //comment by
        callPop.showAtLocation(inflate, Gravity.TOP,0,0);

    }

    /**
     * 根据图片的url路径获得Bitmap对象
     * @param url
     * @return
     */
    private Bitmap returnBitmap(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;

    }


}
